﻿using Compress;
using System;
using System.Collections.Generic;
using UnityEngine;
using Util;

public class VersionsManage : ModelClueInfo
{
    public int VersionsNumber;
    private const string GameVersionsName = "GameVersions.config";
    private const string zipName = "LUA_MAIN.lzma";
    private string urlConfig = "http://localhost/" + GameVersionsName;
    private string urlLuaData = "http://localhost/" + zipName;
    private string NewGameVersions = "New" + GameVersionsName;
    private NetworkManager manager = new NetworkManager();
    public List<Action> queue = new List<Action>();
    private string BasePath;
    private ConfigFileSave Local;
    private HTTPDownLoad df;
    public Action BackCall;

    private ConfigFileSave newConfig;

    public string BasePath1 { get { if (BasePath.isNull()) { BasePath = Application.persistentDataPath + "/"; } return BasePath; } }

    public override void InitModule(GameManage gameManage)
    {
        base.InitModule(gameManage);
    }

    public void Updata(float dt)
    {
        while (queue.Count > 0)
        {
            queue[0].toInvoke();
            queue.RemoveAt(0);
        }
        // if (df != null)
        // {
        //     debug.log(df.Progress.toPercentage(), df.TotalLength);
        // }
    }

    public void ExamineUpData(Action backCall)
    {
        BackCall = backCall;
        var path = BasePath1;
        var name = GameVersionsName;
        var allPath = path + name;
        Local = ConfigFileSave.Load(path, name);
        var cNumber = Local.Get("Versions", "Number");
        Local.Save();
        debug.log(allPath);
        if (cNumber.isTrue())
        {
            if (VersionsNumber < cNumber.toInt())
            {
                VersionsNumber = cNumber.toInt();
            }
        }
        else
        {
            Local.Set("Versions", "Number", VersionsNumber.toString());
        }
        name = NewGameVersions;
        allPath = path + name;

        debug.log("开始 下载");
        df = manager.DownLoadFile(urlConfig, allPath, (s, l, e) =>
        {
            debug.log(" 下载状态 ", s, " 进度 ", l, " 错误", e);
            if (e.isNull())
            {
                newConfig = ConfigFileSave.Load(path, name);
                queue.Add(DownEndNewConfig);
            }
            else
            {
                debug.log("下载错误", e);
            }
            df = null;
        });
    }

    public void DownEndNewConfig()
    {
        var cNumber = newConfig.Get("Versions", "Number");
        var newVi = cNumber.toInt();

        bool isVersionsNumber = newVi > VersionsNumber;
        bool isCache = !LuaFileMgr.IsExamineCache();

        debug.log("isVersionsNumber", isVersionsNumber, "isCache", isCache);
        if (isVersionsNumber || isCache)
        {
            debug.log("有版本更新", (newConfig.Get("Versions", "SIZE").toFloat() / 1024 / 1024).Valid() + "MB");
            Local.Set("Versions", "NewNumber", cNumber);
            Local.Save();
            queue.Add(DownNewVersions);
        }
        else
        {
            newConfig.Delete();
            debug.log("无版本更新");
            queue.Add(EndExamineUpData);
        }
    }

    //下载新包
    private void DownNewVersions()
    {
        debug.log("下载新包");
        var path = BasePath1;
        var name = zipName;
        var allPath = path + name;
        debug.log(urlLuaData, allPath);
        df = manager.DownLoadFile(urlLuaData, allPath, (s, l, e) =>
        {
            debug.log(" 下载状态 ", s, " 进度 ", l, " 错误", e);
            if (e.isNull())
            {
                queue.Add(DownEndNewVersions);
            }
            else
            {
                debug.log("下载错误", e);
            }
            df = null;
        });
    }

    public void DownEndNewVersions()
    {
        var path = BasePath1;
        var name = zipName;
        var allPath = path + name;
        var md5 = FileIO.GetMD5HashFromFile(allPath);
        if (md5.Equals(newConfig.Get("Versions", "MD5")))
        {
            debug.log("MD5 比对完成!");
            queue.Add(Unzip);
        }
        else
        {
            debug.log("MD5 比对失败!文件出现错误");
        }
        newConfig.Delete();
    }

    //解压
    public void Unzip()
    {
        var pathIn = BasePath1 + zipName;
        var pathOut = BasePath1;

        debug.log(pathIn, pathOut);
        FileIO.CreateSavePath(pathOut);

        FileChangeInfo info = new FileChangeInfo();
        info.inpath = pathIn;
        info.outpath = pathOut;
        info.ex = debug.log;
        info.progressDelegate = CompressTool.ShowProgress;
        info.finish = () =>
        {
            FileIO.Delete(pathIn);
            queue.Add(EndExamineUpData);
            FileIO.OpenDirectory(pathOut);
        };
        CompressTool.UnCompress(info);
    }

    //检查结束
    public void EndExamineUpData()
    {
        debug.log("检查结束");
        Local.Set("Versions", "Number", Local.Get("Versions", "NewNumber"));
        VersionsNumber = Local.Get("Versions", "NewNumber").toInt();
        Local.Save();
        queue.Add(BackCall);
    }

    [Button("创建配置文件")]
    public void CreateUpdataAsset()
    {
        LuaFileMgr.JoinCache();
        var pathIn = Application.persistentDataPath + "/Lua";
        var pathOut = PathConfig.Project + "/LuaPack/" + zipName;

        debug.log(pathIn, pathOut);
        if (FileIO.isLoadPath(pathOut))
        {
            FileIO.Delete(pathOut);
        }
        FileIO.CreateSavePath(PathConfig.Project + "/LuaPack/");

        FileChangeInfo info = new FileChangeInfo();
        info.inpath = pathIn;
        info.outpath = pathOut;
        info.ex = debug.log;
        info.progressDelegate = CompressTool.ShowProgress;
        info.finish = () =>
        {
            var ConfigPath = PathConfig.Project + "/LuaPack/";
            var Config = ConfigFileSave.Load(ConfigPath, GameVersionsName);

            var md5 = FileIO.GetMD5HashFromFile(pathOut);
            var size = FileIO.FileSize(pathOut);

            Config.Set("Versions", "Number", VersionsNumber.toString());
            Config.Set("Versions", "MD5", md5);
            Config.Set("Versions", "SIZE", size.ToString());
            Config.Save();

            FileIO.OpenDirectory(PathConfig.Project + "/LuaPack");
        };
        CompressTool.Compress(info);
    }

    [Button("打开缓存")]
    public void CreatePersistentDataPath()
    {
        FileIO.OpenDirectory(Application.persistentDataPath);
    }
}